﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Metro.Core;

namespace Clock
{
    /// <summary>
    /// Interaction logic for Clock.xaml
    /// </summary>
    public partial class WidgetControl
    {
        private DispatcherTimer _timer;
        private Options _options;

        public WidgetControl()
        {
            InitializeComponent();

        }

        public void Load()
        {
            _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
            _timer.Tick += TimerTick;
            _timer.Start();

            UpdateSettings();

            var optionsItem = new MenuItem {Header = Widget.Instance.LocaleManager.GetString("Options")};
            optionsItem.Click += OptionsItemClick;
            Widget.Instance.AddMenuItem(optionsItem);

            _options = new Options();
        }

        void OptionsItemClick(object sender, RoutedEventArgs e)
        {
            if (_options.IsVisible)
            {
                _options.Activate();
                return;
            }
            _options = new Options();

            if (E.Locale == "he-IL" || E.Locale == "ar-SA")
            {
                _options.FlowDirection = FlowDirection.RightToLeft;
            }
            else
            {
                _options.FlowDirection = FlowDirection.LeftToRight;
            }

            _options.ShowDialog();
        }

        void TimerTick(object sender, EventArgs e)
        {
            if (Widget.Instance.Sett.TimeMode == 1)
            {
                Hours.Text = DateTime.Now.ToString("HH");
                Minutes.Text = DateTime.Now.ToString("mm");
            }
            else
            {
                Hours.Text = DateTime.Now.ToString("hh");
                Minutes.Text = DateTime.Now.ToString("mm");
            }

            AmPm.Text = DateTime.Now.ToString("tt");
        }

        public void UpdateSettings()
        {
            if (Widget.Instance.Sett.TimeMode == 1)
            {
                Hours.Text = DateTime.Now.ToString("HH");
                Minutes.Text = DateTime.Now.ToString("mm");

                AmPm.Visibility = Visibility.Collapsed;
            }
            else
            {
                Hours.Text = DateTime.Now.ToString("hh");
                Minutes.Text = DateTime.Now.ToString("mm");

                AmPm.Visibility = Visibility.Visible;
            }

            AmPm.Text = DateTime.Now.ToString("tt");
        }
    }
}
